import type { Context } from 'koa';
import { RefreshTokenDto } from '@/dtos/refreshToken.dto';
import { NoPermissionErrors } from '@/enums/responseErrors';
import { verifyRefreshToken } from '@/helpers/tokenVerify';
import { generateToken } from '@/helpers/generateToken';

// 刷新token
export const refreshTokenController = async (ctx: Context) => {
  const input = ctx.request.body;
  const params = await ctx.vailParams<RefreshTokenDto>(RefreshTokenDto, input);

  const refreshToken = params.refreshToken;
  const verify = await verifyRefreshToken(refreshToken);

  if (verify === false) {
    ctx.sendError(NoPermissionErrors.tokenExpired);
    return;
  }

  const result = generateToken({
    userId: verify.userId,
    createAt: Date.now()
  });

  ctx.sendSuccess(result);
}